package com.yao2san.sim.storage.client.config;

import com.yao2san.sim.storage.client.util.StorageUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.io.File;

@Configuration
@Import(LocalProperties.class)
@ConditionalOnProperty(prefix = "sim.storage", name = "type", havingValue = "local")
@Slf4j
public class ResourceMappingConfig implements WebMvcConfigurer {

    private final LocalProperties localProperties;

    public ResourceMappingConfig(LocalProperties localProperties) {
        this.localProperties = localProperties;
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        String prefix = localProperties.getPrefix();
        String bucket = localProperties.getBucket();
        String mapping = prefix + "/**";
        String resourceLocation = "file:" + StorageUtil.formatPath(bucket) + File.separator;
        registry.addResourceHandler(mapping).addResourceLocations(resourceLocation);
    }
}